<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>绘制图表</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        .container {
            width: 80%;
            margin: 100px auto;
            padding: 20px;
            background: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
        }

        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }

        canvas {
            display: block;
            margin: 0 auto;
        }

        #back-button {
            padding: 10px 20px;
            background: #5cb85c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: block;
            margin: 20px auto;
            text-align: center;
            text-decoration: none;
        }

        #back-button:hover {
            background: #4cae4c;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>绘制图表</h2>
    <canvas id="chartCanvas" width="400" height="400"></canvas>
    <button id="back-button" onclick="window.location.href='/result/'">返回</button>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const chartType = localStorage.getItem('chartType');
        const queryResults = JSON.parse(localStorage.getItem('queryResults'));

        if (chartType && queryResults) {
            const labels = queryResults.data.map((row, index) => index + 1); // 用数据索引作为标签
            const data = queryResults.data.map(row => row[1]); // 假设要绘制第二列的数据

            const ctx = document.getElementById('chartCanvas').getContext('2d');
            new Chart(ctx, {
                type: chartType,
                data: {
                    labels: labels,
                    datasets: [{
                        label: '数据',
                        data: data,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // 清除存储的图表类型
            localStorage.removeItem('chartType');
        } else {
            document.querySelector('.container').innerHTML = '<p>没有查询到数据或未选择图表类型</p>';
        }
    });
</script>
</body>
</html>
